package fiszkas

import grails.converters.JSON
import groovy.json.JsonSlurper

class LessonController {

    static defaultAction = "prompt"

    static random = new Random()

    def probabilities = [
//            3: 3,
//            2: 4,
//            1: 6,
//            0: 12,
            3: 2,
            2: 3,
            1: 5,
            0: 8,
    ]

    def prompt() {

        Map boxes = [:]
        Fiszka.MAX_BOXES.times { boxNo ->
            int count = Fiszka.countByBox(boxNo)
            if (count > 0)
                boxes[boxNo] = count
        }

        println boxes

        // multiply size by probability and sort
        int sum = 0
        boxes = new TreeMap(boxes.collectEntries { entry ->
            int prob = entry.value * probabilities[entry.key]
            sum += prob
            [(entry.key): prob]
        })

        println sum
        println boxes

        int randInt = random.nextInt(sum)

        int box = -1
        int rand = randInt
        while (rand >= 0) {
            rand -= boxes[++box]
        }

        println box

        def fiszka = Fiszka.findAll("from Fiszka as f where f.box=? order by f.lastPracticed",
                [box], [max: 1, order: 'desc'])[0]

        println fiszka

        [fiszka: fiszka, diag: "probs=${boxes} sum=$sum rand=$randInt box=$box"]
    }

    def show() {
        def fiszka = Fiszka.get(params.fiszkaId)

        [fiszka: fiszka]
    }

    def fetchImg() {

        def fiszka = Fiszka.get(params.fiszkaId)

        def src = fetchThumbnailUrl(fiszka)

        def json = ['src': src]
        render json as JSON
    }

    private String fetchThumbnailUrl(Fiszka fiszka) {

        try {

            def accountKey = '1F1GLq0ikIR1zuD7elqI2sJPatpUHGhSzG2+4eiaelI'
            def authString = "$accountKey:$accountKey".getBytes().encodeBase64().toString()
            def query = URLEncoder.encode(fiszka.english, "ISO-8859-1")

            println query

            URLConnection connection = new URL('https://api.datamarket.azure.com/Bing/Search/Image?$top=1&$format=json&Query=%27' + query + '%27').openConnection()
            connection.setRequestProperty("Authorization", "Basic ${authString}")
            def data = connection.content.text

            //println "DATA=$data"

            def json = new JsonSlurper().parseText(data)
            // TODO
            //println json.find { it.getKey() == 'MediaUrl' }
            def src = json.d.results[0].Thumbnail.MediaUrl

            println "SRC=$src"

            return src

        } catch (e) {
            e.printStackTrace()
        }
    }

    def hint() {
        def fiszka = Fiszka.get(params.fiszkaId)

        def words = fiszka.english.split(',')

        def hints = words.collect {
            (it =~ /(\w)\w*(\w)/).replaceAll('$1...$2')
        }

        [fiszka: fiszka, hint: hints.join(',')]
    }

    def correct() {

        def fiszka = Fiszka.get(params.fiszkaId)
        fiszka.inc()
        fiszka.save()

        redirect action: 'prompt'
    }

    def incorrect() {

        def fiszka = Fiszka.get(params.fiszkaId)
        fiszka.dec()
        fiszka.save()

        redirect action: 'prompt'
    }
}
